BUILD:=./build

CFLAGS:= -m32
CFLAGS+= -masm=intel
CFLAGS+= -fno-builtin
CFLAGS+= -nostdinc
CFLAGS+= -fno-pic
CFLAGS+= -fno-pie
CFLAGS+= -nostdlib
CFLAGS+= -fno-stack-protector
CFLAGS+= -I ./oskernel/include
CFLAGS+= $(strip ${CFLAGS})

DEBUG:= -g

HD_IMG_NAME:="hd.img"

all: $(BUILD)/boot/boot.bin $(BUILD)/boot/setup.bin $(BUILD)/system.bin
	$(shell rm -rf $(BUILD)/$(HD_IMG_NAME))
	bximage -q -hd=16 -func=create -sectsize=512 -imgmode=flat $(BUILD)/$(HD_IMG_NAME)
	dd if=${BUILD}/boot/boot.bin of=$(BUILD)/$(HD_IMG_NAME) bs=512 seek=0 count=1 conv=notrunc
	dd if=${BUILD}/boot/setup.bin of=$(BUILD)/$(HD_IMG_NAME) bs=512 seek=1 count=2 conv=notrunc
	dd if=${BUILD}/system.bin of=$(BUILD)/$(HD_IMG_NAME) bs=512 seek=3 count=30 conv=notrunc

$(BUILD)/system.bin: $(BUILD)/kernel.bin
	objcopy -O binary $(BUILD)/kernel.bin $(BUILD)/system.bin
	nm $(BUILD)/kernel.bin | sort > $(BUILD)/system.map

$(BUILD)/kernel.bin: $(BUILD)/boot/head.o $(BUILD)/init/main.o \
    $(BUILD)/kernel/asm/io.o $(BUILD)/kernel/chr_drv/console.o \
	$(BUILD)/kernel/lib/string.o 
	ld -m elf_i386 $^ -o $@ -Ttext 0x1200

$(BUILD)/boot/head.o: oskernel/boot/head.asm
	nasm -f elf32 -g $< -o $@

$(BUILD)/boot/%.bin: oskernel/boot/%.asm
	$(shell mkdir -p $(BUILD)/boot)
	nasm $< -o $@

$(BUILD)/kernel/asm/%.o: oskernel/kernel/asm/%.S
	$(shell mkdir -p ${BUILD}/kernel/asm)
	gcc ${CFLAGS} ${DEBUG} -c $< -o $@

$(BUILD)/init/main.o: oskernel/init/main.c
	$(shell mkdir -p $(BUILD)/init)
	gcc $(CFLAGS) $(DEBUG) -c $< -o $@

${BUILD}/kernel/chr_drv/%.o: oskernel/kernel/chr_drv/%.c
	$(shell mkdir -p ${BUILD}/kernel/chr_drv)
	gcc ${CFLAGS} ${DEBUG} -c $< -o $@

$(BUILD)/kernel/lib/%.o: oskernel/kernel/lib/%.c
	$(shell mkdir -p ${BUILD}/kernel/lib)
	gcc ${CFLAGS} ${DEBUG} -c $< -o $@

clean:
	$(shell rm -rf $(BUILD))

qemu: all
	qemu-system-i386 \
	-m 32M \
	-boot d \
	-cpu Haswell \
	-hda ./build/hd.img 